package org.spider.resolver;

import cn.hutool.core.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.spider.annotation.SpiderParamBind;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.lang.reflect.Parameter;


@Slf4j
public class ModelResolver implements HandlerMethodArgumentResolver {

    private ModelLoaderRegisteCenter registeCenter;

    public ModelResolver (ModelLoaderRegisteCenter registeCenter){
        this.registeCenter = Assert.notNull(registeCenter);
    }

    public boolean supportsParameter(MethodParameter methodParameter) {
        if(registeCenter.getLoaders().isEmpty()) return false;
        SpiderParamBind parameterAnnotation = methodParameter.getParameterAnnotation(SpiderParamBind.class);
        return parameterAnnotation != null && registeCenter.getDesignationLoader(methodParameter.getParameterType()) != null;
    }

    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        SpiderParamBind paramBind = methodParameter.getParameterAnnotation(SpiderParamBind.class);
        String value = paramBind.value();
        String requestParameter = nativeWebRequest.getParameter(value);
        ModelLoader modelLoader = registeCenter.getDesignationLoader(methodParameter.getParameterType());
        if(modelLoader == null) return null;
        return modelLoader.load(requestParameter);
    }
}